package com.stores.action;

import java.util.ArrayList;
import java.util.List;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.stores.model.Category;
import com.stores.model.Datastore;

public class ManageCategoryAction {

	/**
	 * 
	 * @param category
	 */
	public void Create(Category category) {
		DatastoreService datastore = Datastore.get();
		Entity categoryEntity = new Entity(Category.class.getSimpleName());
		categoryEntity.setProperty("name", category.getName());
		categoryEntity.setProperty("description", category.getDescription());
		categoryEntity.setProperty("parentId", category.getParentId());

		datastore.put(categoryEntity);
	}

	/**
	 * 
	 * @param category
	 * @return
	 */
	public boolean Update(Category category) {
		DatastoreService datastore = Datastore.get();
		Query categoryQuery = new Query(Category.class.getSimpleName());
		categoryQuery.addFilter(
				Entity.KEY_RESERVED_PROPERTY,
				FilterOperator.EQUAL,
				KeyFactory.createKey(Category.class.getSimpleName(),
						category.getId()));
		PreparedQuery query = datastore.prepare(categoryQuery);
		Entity categoryEntity = query.asSingleEntity();
		if (categoryEntity == null) {
			return false;
		} else {
			categoryEntity.setProperty("name", category.getName());
			categoryEntity
					.setProperty("description", category.getDescription());
			categoryEntity.setProperty("parentId", category.getParentId());
			datastore.put(categoryEntity);
		}
		return true;
	}

	/**
	 * 
	 * @return
	 */
	public List<Category> Retrive() {
		DatastoreService datastore = Datastore.get();
		Query entityQuery = new Query(Category.class.getSimpleName());
		PreparedQuery query = datastore.prepare(entityQuery);
		Iterable<Entity> categoryEntities = query.asIterable();

		List<Category> categories = new ArrayList<Category>();

		for (Entity c : categoryEntities) {
			Category category = new Category();
			category.setId(c.getKey().getId());
			category.setName(c.getProperty("name").toString());
			category.setDescription(c.getProperty("description").toString());
			category.setParentId(Long.parseLong(c.getProperty("parentId")
					.toString()));
			categories.add(category);
		}
		return categories;
	}

}
